package com.cdc.taskhandler;

import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

public class PBarAsyncTaskActivity extends AppCompatActivity {

    private ProgressBar linPbar;
    private PBarAsyncTask pBarAsyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pbar_async_task);

        linPbar=findViewById(R.id.linPbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pBarAsyncTask=new PBarAsyncTask(linPbar);
                pBarAsyncTask.execute();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(pBarAsyncTask!=null && pBarAsyncTask.getStatus()==AsyncTask.Status.RUNNING){
            //cancle()方法只是将对应的AsyncTask标记为cancle状态，并不是真正的取消线程的执行
            pBarAsyncTask.cancel(true);
        }
    }


}

class PBarAsyncTask extends AsyncTask<Void,Integer,Void> {
    private ProgressBar linPbar;
    public PBarAsyncTask(ProgressBar linPbar) {
        this.linPbar = linPbar;
        linPbar.setMax(100);
    }
    @Override
    protected Void doInBackground(Void... voids) {
        for(int i=1;i<=100;i++){
            //如果isCancelled()返回true,则表示此任务已经被标记为cancle状态了，则此时立即停止后面的操作
            if(isCancelled()){
                break;
            }
            publishProgress(i);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if(isCancelled()){
            return;
        }

        linPbar.setProgress(values[0]);
    }

}
